<template>
  <!-- 头像模式：小图片显示 -->
  <view v-if="!visible" class="avatar-container" @click="openPreview">
    <!-- 有图片时显示图片 -->
    <image 
      v-if="avatarSrc"
      :src="avatarSrc" 
      :alt="alt"
      class="avatar-image"
      :class="avatarClass"
      :style="avatarStyle"
      mode="aspectFill"
      @error="handleImageError"
    />
    <!-- 没有图片时显示默认头像图标 -->
    <view 
      v-else
      class="avatar-placeholder"
      :class="avatarClass"
      :style="avatarStyle"
    >
      <uni-icons type="person-filled" :size="Math.min(width, height) * 0.6" color="#999"></uni-icons>
    </view>
  </view>

  <!-- 预览模式：全屏预览 -->
  <view v-if="visible" class="image-preview-modal" @click="handleMaskClick">
    <!-- 遮罩层 -->
    <view class="preview-mask"></view>
    
    <!-- 内容区域 -->
    <view class="preview-content" @click.stop>
      <!-- 关闭按钮 -->
      <view class="preview-close" @click="closePreview">
        <uni-icons type="close" size="20" color="#fff"></uni-icons>
      </view>
      
      <!-- 操作工具栏 -->
      <view class="preview-toolbar">
        <view class="toolbar-inner">
          <view class="tool-btn" @click="zoomOut" :class="{ disabled: scale <= 0.2 }">
            <uni-icons type="minus" size="16" color="#fff"></uni-icons>
          </view>
          <view class="tool-btn" @click="resetTransform">
            <text class="zoom-text">{{ Math.round(scale * 100) }}%</text>
          </view>
          <view class="tool-btn" @click="zoomIn" :class="{ disabled: scale >= 3 }">
            <uni-icons type="plus" size="16" color="#fff"></uni-icons>
          </view>
          <view class="tool-btn" @click="rotateLeft">
            <uni-icons type="undo" size="16" color="#fff"></uni-icons>
          </view>
          <view class="tool-btn" @click="rotateRight">
            <uni-icons type="redo" size="16" color="#fff"></uni-icons>
          </view>
          <view class="tool-btn" @click="downloadCurrentImage">
            <uni-icons type="download" size="16" color="#fff"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 导航按钮 -->
      <view v-if="previewSrcList.length > 1" class="preview-navigation">
        <view 
          class="nav-btn nav-prev" 
          @click="prevImage" 
          :class="{ disabled: internalCurrentIndex === 0 }"
        >
          <uni-icons type="left" size="20" color="#fff"></uni-icons>
        </view>
        <view 
          class="nav-btn nav-next" 
          @click="nextImage" 
          :class="{ disabled: internalCurrentIndex === previewSrcList.length - 1 }"
        >
          <uni-icons type="right" size="20" color="#fff"></uni-icons>
        </view>
      </view>
      
      <!-- 图片容器 -->
      <view class="preview-container">
        <image 
          :src="currentImageSrc" 
          class="preview-image"
          :style="imageStyle"
          mode="aspectFit"
          @load="onImageLoad"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        />
      </view>
      
      <!-- 图片信息 -->
      <view class="preview-info">
        <text class="image-name">{{ currentImageName }}</text>
        <text class="image-index" v-if="previewSrcList.length > 1">
          {{ internalCurrentIndex + 1 }}/{{ previewSrcList.length }}
        </text>
      </view>
      
      <!-- 缩略图导航 -->
      <view v-if="previewSrcList.length > 1 && showThumbnails" class="preview-thumbnails">
        <scroll-view class="thumbnails-scroll" scroll-x>
          <view class="thumbnails-list">
            <view 
              v-for="(src, index) in previewSrcList" 
              :key="index" 
              class="thumbnail-item" 
              :class="{ active: index === internalCurrentIndex }"
              @click="switchToImage(index)"
            >
              <image :src="src" class="thumbnail-image" mode="aspectFill" />
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ImagePreview',
  props: {
    // 图片源 - 支持字符串（逗号分割）或数组
    src: {
      type: [String, Array],
      default: ''
    },
    // 当前显示的图片索引
    currentIndex: {
      type: Number,
      default: 0
    },
    // 是否显示缩略图
    showThumbnails: {
      type: Boolean,
      default: true
    },
    // 是否可见（预览模式）
    visible: {
      type: Boolean,
      default: false
    },
    // 头像模式相关属性
    width: {
      type: [Number, String],
      default: 40
    },
    height: {
      type: [Number, String],
      default: 40
    },
    borderRadius: {
      type: String,
      default: '50%'
    },
    // 图片描述
    alt: {
      type: String,
      default: '头像'
    },
    // 是否启用预览功能
    preview: {
      type: Boolean,
      default: true
    }
  },
  emits: ['close', 'change', 'open'],
  data() {
    return {
      // 图片变换状态
      scale: 1,
      rotation: 0,
      translateX: 0,
      translateY: 0,
      
      // 触摸相关
      touchStartDistance: 0,
      touchStartScale: 1,
      touchStartX: 0,
      touchStartY: 0,
      touchStartTranslateX: 0,
      touchStartTranslateY: 0,
      isTouching: false,
      touchCount: 0,
      
      // 内部索引状态
      internalCurrentIndex: this.currentIndex
    }
  },
  computed: {
    // 解析src为数组格式
    parsedSrcList() {
      if (!this.src) return []
      
      // 如果src是数组，直接返回
      if (Array.isArray(this.src)) {
        return this.src.filter(url => url && url.trim())
      }
      
      // 如果src是字符串，按逗号分割
      if (typeof this.src === 'string') {
        return this.src.split(',')
          .map(url => url.trim())
          .filter(url => url)
      }
      
      return []
    },
    
    // 头像显示的图片源（显示第一张）
    avatarSrc() {
      if (this.parsedSrcList.length > 0) {
        return this.parsedSrcList[0]
      }
      return ''
    },
    
    // 预览时使用的图片源列表
    previewSrcList() {
      return this.parsedSrcList
    },
    currentImageSrc() {
      if (this.previewSrcList.length === 0) return ''
      return this.previewSrcList[this.internalCurrentIndex] || ''
    },
    currentImageName() {
      if (!this.currentImageSrc) return ''
      const parts = this.currentImageSrc.split('/')
      return parts[parts.length - 1] || '图片'
    },
    imageStyle() {
      return {
        transform: `scale(${this.scale}) rotate(${this.rotation}deg) translate(${this.translateX}px, ${this.translateY}px)`,
        transition: this.isTouching ? 'none' : 'transform 0.3s ease'
      }
    },
    // 头像容器样式
    avatarStyle() {
      const width = typeof this.width === 'number' ? `${this.width}rpx` : this.width
      const height = typeof this.height === 'number' ? `${this.height}rpx` : this.height
      return {
        width,
        height,
        borderRadius: this.borderRadius
      }
    },
    // 头像图片样式类
    avatarClass() {
      return {
        'avatar-clickable': this.preview
      }
    }
  },
  watch: {
    currentIndex(newVal) {
      this.internalCurrentIndex = newVal
      this.resetTransform()
    },
    visible(newVal) {
      if (newVal) {
        this.internalCurrentIndex = this.currentIndex
        this.resetTransform()
      }
    }
  },
  methods: {
    // 打开预览
    openPreview() {
      if (!this.preview || !this.avatarSrc) return
      this.internalCurrentIndex = 0
      this.resetTransform()
      this.$emit('open')
    },
    
    // 关闭预览
    closePreview() {
      this.$emit('close')
    },
    
    // 点击遮罩关闭
    handleMaskClick() {
      this.closePreview()
    },
    
    // 图片加载错误处理
    handleImageError() {
      console.warn('头像加载失败:', this.avatarSrc)
    },
    
    // 重置变换
    resetTransform() {
      this.scale = 1
      this.rotation = 0
      this.translateX = 0
      this.translateY = 0
    },
    
    // 放大
    zoomIn() {
      if (this.scale < 3) {
        this.scale += 0.2
      }
    },
    
    // 缩小
    zoomOut() {
      if (this.scale > 0.2) {
        this.scale -= 0.2
      }
    },
    
    // 逆时针旋转
    rotateLeft() {
      this.rotation -= 90
    },
    
    // 顺时针旋转
    rotateRight() {
      this.rotation += 90
    },
    
    // 上一张图片
    prevImage() {
      if (this.internalCurrentIndex > 0) {
        this.internalCurrentIndex--
        this.resetTransform()
        this.$emit('change', this.internalCurrentIndex)
      }
    },
    
    // 下一张图片
    nextImage() {
      if (this.internalCurrentIndex < this.previewSrcList.length - 1) {
        this.internalCurrentIndex++
        this.resetTransform()
        this.$emit('change', this.internalCurrentIndex)
      }
    },
    
    // 切换到指定图片
    switchToImage(index) {
      if (index >= 0 && index < this.previewSrcList.length && index !== this.internalCurrentIndex) {
        this.internalCurrentIndex = index
        this.resetTransform()
        this.$emit('change', index)
      }
    },
    
    // 下载当前图片
    downloadCurrentImage() {
      if (!this.currentImageSrc) return
      
      uni.downloadFile({
        url: this.currentImageSrc,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({
                  title: '保存成功',
                  icon: 'success'
                })
              },
              fail: () => {
                uni.showToast({
                  title: '保存失败',
                  icon: 'error'
                })
              }
            })
          }
        },
        fail: () => {
          uni.showToast({
            title: '下载失败',
            icon: 'error'
          })
        }
      })
    },
    
    // 图片加载完成
    onImageLoad() {
      // 可以在这里添加图片加载完成后的逻辑
    },
    
    // 触摸开始
    handleTouchStart(e) {
      this.isTouching = true
      this.touchCount = e.touches.length
      
      if (e.touches.length === 1) {
        // 单点触摸 - 拖拽
        this.touchStartX = e.touches[0].clientX
        this.touchStartY = e.touches[0].clientY
        this.touchStartTranslateX = this.translateX
        this.touchStartTranslateY = this.translateY
      } else if (e.touches.length === 2) {
        // 双点触摸 - 缩放
        const touch1 = e.touches[0]
        const touch2 = e.touches[1]
        this.touchStartDistance = this.getDistance(touch1, touch2)
        this.touchStartScale = this.scale
      }
    },
    
    // 触摸移动
    handleTouchMove(e) {
      if (!this.isTouching) return
      
      e.preventDefault()
      
      if (e.touches.length === 1 && this.touchCount === 1) {
        // 单点拖拽
        const deltaX = e.touches[0].clientX - this.touchStartX
        const deltaY = e.touches[0].clientY - this.touchStartY
        this.translateX = this.touchStartTranslateX + deltaX
        this.translateY = this.touchStartTranslateY + deltaY
      } else if (e.touches.length === 2) {
        // 双点缩放
        const touch1 = e.touches[0]
        const touch2 = e.touches[1]
        const distance = this.getDistance(touch1, touch2)
        const scaleRatio = distance / this.touchStartDistance
        this.scale = Math.max(0.2, Math.min(3, this.touchStartScale * scaleRatio))
      }
    },
    
    // 触摸结束
    handleTouchEnd(e) {
      this.isTouching = false
      this.touchCount = 0
    },
    
    // 计算两点间距离
    getDistance(touch1, touch2) {
      const dx = touch1.clientX - touch2.clientX
      const dy = touch1.clientY - touch2.clientY
      return Math.sqrt(dx * dx + dy * dy)
    }
  }
}
</script>

<style lang="scss" scoped>
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 9998;
}

.preview-content {
  position: relative;
  z-index: 9999;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.preview-close {
  position: absolute;
  top: 60rpx;
  right: 60rpx;
  width: 80rpx;
  height: 80rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  transition: all 0.3s;
  
  &:active {
    background: rgba(0, 0, 0, 0.8);
  }
}

.preview-toolbar {
  position: absolute;
  bottom: 200rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10000;
}

.toolbar-inner {
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50rpx;
  padding: 16rpx 24rpx;
  gap: 16rpx;
}

.tool-btn {
  width: 80rpx;
  height: 80rpx;
  background: transparent;
  border-radius: 50%;
  color: white;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  
  &:active:not(.disabled) {
    background: rgba(255, 255, 255, 0.2);
  }
  
  &.disabled {
    opacity: 0.3;
  }
  
  .zoom-text {
    font-size: 24rpx;
    font-weight: bold;
    color: #fff;
  }
}

.preview-navigation {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between;
  pointer-events: none;
  z-index: 10000;
  padding: 0 60rpx;
}

.nav-btn {
  width: 100rpx;
  height: 100rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  color: white;
  font-size: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  pointer-events: all;
  
  &:active:not(.disabled) {
    background: rgba(0, 0, 0, 0.8);
  }
  
  &.disabled {
    opacity: 0.3;
  }
}

.preview-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  overflow: hidden;
  padding: 120rpx 60rpx;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 16rpx;
}

.preview-info {
  position: absolute;
  top: 60rpx;
  left: 60rpx;
  z-index: 10000;
  
  .image-name {
    display: block;
    font-size: 28rpx;
    color: white;
    font-weight: 500;
    margin-bottom: 8rpx;
    max-width: 400rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .image-index {
    display: block;
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.preview-thumbnails {
  position: absolute;
  bottom: 60rpx;
  left: 0;
  right: 0;
  z-index: 10000;
  padding: 0 60rpx;
}

.thumbnails-scroll {
  width: 100%;
  white-space: nowrap;
}

.thumbnails-list {
  display: flex;
  gap: 16rpx;
  justify-content: center;
  padding: 20rpx 0;
}

.thumbnail-item {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  overflow: hidden;
  border: 4rpx solid transparent;
  transition: border-color 0.3s ease;
  flex-shrink: 0;
  
  &.active {
    border-color: #409eff;
  }
  
  .thumbnail-image {
    width: 100%;
    height: 100%;
  }
}

/* 头像模式样式 */
.avatar-container {
  display: inline-block;
  overflow: hidden;
  position: relative;
  
  .avatar-image {
    width: 100%;
    height: 100%;
    display: block;
    
    &.avatar-clickable {
      cursor: pointer;
      transition: transform 0.2s ease;
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
  
  .avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    
    &.avatar-clickable {
      cursor: pointer;
      transition: transform 0.2s ease;
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
}
</style>